"""
仪表盘页面
"""

from flask import render_template, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import Appointment, Resource, User, SchedulingResult
from app.web import web_bp
from datetime import datetime, timedelta

@web_bp.route('/')
@web_bp.route('/dashboard')
@jwt_required()
def dashboard():
    """主仪表盘"""
    return render_template('dashboard.html')

@web_bp.route('/api/dashboard/stats')
@jwt_required()
def dashboard_stats():
    """获取仪表盘统计数据"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role not in ['admin', 'doctor']:
        return jsonify({'error': '无权限访问'}), 403
    
    # 获取今日统计
    today = datetime.now().date()
    today_start = datetime.combine(today, datetime.min.time())
    today_end = datetime.combine(today, datetime.max.time())
    
    # 预约统计
    total_appointments = Appointment.query.count()
    today_appointments = Appointment.query.filter(
        Appointment.scheduled_time >= today_start,
        Appointment.scheduled_time <= today_end
    ).count()
    
    pending_appointments = Appointment.query.filter_by(status='pending').count()
    confirmed_appointments = Appointment.query.filter_by(status='confirmed').count()
    
    # 资源统计
    total_resources = Resource.query.count()
    available_resources = Resource.query.filter_by(status='available').count()
    occupied_resources = Resource.query.filter_by(status='occupied').count()
    
    # 资源利用率
    resource_utilization = db.session.query(
        db.func.avg(SchedulingResult.resource_utilization)
    ).filter(
        SchedulingResult.created_at >= today_start
    ).scalar() or 0
    
    # 患者等待时间
    avg_wait_time = db.session.query(
        db.func.avg(SchedulingResult.patient_wait_time)
    ).filter(
        SchedulingResult.created_at >= today_start
    ).scalar() or 0
    
    # 最近调度结果
    recent_schedules = SchedulingResult.query.order_by(
        SchedulingResult.created_at.desc()
    ).limit(5).all()
    
    recent_schedule_list = []
    for schedule in recent_schedules:
        recent_schedule_list.append({
            'id': schedule.id,
            'algorithm': schedule.algorithm_used,
            'utilization': schedule.resource_utilization,
            'wait_time': schedule.patient_wait_time,
            'fairness': schedule.fairness_score,
            'created_at': schedule.created_at.isoformat()
        })
    
    return jsonify({
        'appointments': {
            'total': total_appointments,
            'today': today_appointments,
            'pending': pending_appointments,
            'confirmed': confirmed_appointments
        },
        'resources': {
            'total': total_resources,
            'available': available_resources,
            'occupied': occupied_resources
        },
        'performance': {
            'resource_utilization': round(resource_utilization, 2),
            'avg_wait_time': round(avg_wait_time, 2)
        },
        'recent_schedules': recent_schedule_list
    })

@web_bp.route('/api/dashboard/charts')
@jwt_required()
def dashboard_charts():
    """获取图表数据"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    # 权限检查
    if user.role not in ['admin', 'doctor']:
        return jsonify({'error': '无权限访问'}), 403
    
    # 获取最近7天的数据
    end_date = datetime.now()
    start_date = end_date - timedelta(days=7)
    
    # 预约趋势
    appointment_trend = []
    for i in range(7):
        date = start_date + timedelta(days=i)
        count = Appointment.query.filter(
            db.func.date(Appointment.scheduled_time) == date.date()
        ).count()
        appointment_trend.append({
            'date': date.strftime('%Y-%m-%d'),
            'count': count
        })
    
    # 资源利用率趋势
    utilization_trend = []
    for i in range(7):
        date = start_date + timedelta(days=i)
        avg_utilization = db.session.query(
            db.func.avg(SchedulingResult.resource_utilization)
        ).filter(
            db.func.date(SchedulingResult.created_at) == date.date()
        ).scalar() or 0
        
        utilization_trend.append({
            'date': date.strftime('%Y-%m-%d'),
            'utilization': round(avg_utilization, 2)
        })
    
    # 资源类型分布
    resource_distribution = db.session.query(
        Resource.resource_type,
        db.func.count(Resource.id).label('count')
    ).group_by(Resource.resource_type).all()
    
    resource_dist = []
    for resource_type, count in resource_distribution:
        resource_dist.append({
            'type': resource_type,
            'count': count
        })
    
    return jsonify({
        'appointment_trend': appointment_trend,
        'utilization_trend': utilization_trend,
        'resource_distribution': resource_dist
    })
